#include <stdlib.h>
#include <stdint.h>

typedef struct entry {
	uint64_t id;
	uint64_t offLen;
	struct entry *next;
} entry_t;

typedef struct keydir {
	uint32_t size;
	struct entry **table;
} keydir_t;

keydir_t* init_keydir(uint32_t size) {
	keydir_t *kd = malloc(sizeof(keydir_t));
	kd->size = size;
	kd->table = (entry_t **) calloc(size, sizeof(struct Entry *));
	return 0;
}

void destroy_keydir(keydir_t *kd) {
	int i;
	for (i = 0; i < kd->size; i++) {
		entry_t *e = kd->table[i], *tmp;
		while (e) {
			tmp = e;
			e = e->next;
			free(tmp);
		}
	}
	free(kd);
}

int put_keydir(keydir_t *kd, uint64_t id, uint64_t offLen) {
	entry_t *e = malloc(sizeof(entry_t));
	e->id = id;
	e->offLen = offLen;
	e->next = kd->table[id % kd->size];
	kd->table[id % kd->size] = e;
	return 0;
}

uint64_t get_keydir(keydir_t *kd, uint64_t id) {
	entry_t *e = kd->table[id % kd->size];
	while (e != NULL) {
		if (e->id == id) return e->offLen;
		e = e->next;
	}

	return 0;
}
